package origin

import (
	"golang.org/x/net/websocket"
	"sync"
	"tradove/blockchain/src/github.com/sirupsen/logrus"
)

type WsClient struct {
	Host string
}

func (this *WsClient) SendMessages(message string) {
	var data string

	logrus.Info("host: ", this.Host)

	conn, err := websocket.Dial("ws://" + this.Host + "/ws_msg", "ws", "http://" + this.Host + "/")
	if err != nil {
		logrus.Error("client connect to server error: ", err.Error())
	}

	gLocker := new(sync.Mutex)
	cond := sync.NewCond(gLocker)
	cond.L.Lock()
	defer cond.L.Unlock()

	logrus.Info("write message: ", message, " to server")
	err = websocket.Message.Send(conn, message)
	if err != nil {
		logrus.Error("client send message to server error: ", err.Error())
	}

	go func(){
		err = websocket.Message.Receive(conn, &data)
		if err != nil {
			logrus.Error("get ws server message error: ", err.Error())
		}
		logrus.Info("message from server: ", data)
		cond.Signal()
	}()

	logrus.Info("cond wait signal to rouse")
	for {
		cond.Wait()
		break
	}
	logrus.Info("client finish")
}
